<template>
  <div class="jsonCodeRoot">
    <mci-label class="py-8"> 请求参数 </mci-label>
    <el-card shadow="never" class="w-full">
      <div id="apiJsonCode" class="w-full h-120" style="overflow: auto"></div>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { onMounted } from 'vue';
import { MciLabel } from '@/components/base';
import { EditorState, Compartment } from '@codemirror/state';
import { basicSetup } from 'codemirror';
import { EditorView } from '@codemirror/view';
// import { json } from '@codemirror/lang-json';
import { json5 } from 'codemirror-json5';
import { ElCard } from 'element-plus';

let tabSize = new Compartment();
let startState = EditorState.create({
  doc: '',
  extensions: [basicSetup, json5(), tabSize.of(EditorState.tabSize.of(8))]
});

let view: any;

onMounted(() => {
  view = new EditorView({
    state: startState,
    parent: document.getElementById('apiJsonCode') as Element // document.body
  });
});

// 清空数据
const clearData = () => {
  const docStr = view.state.doc.toString();
  if (docStr) {
    let transaction = view.state.update({ changes: { from: 0, to: docStr.length } });
    view.dispatch(transaction);
  }
};

// 设置数据
const setData = (data: string) => {
  try {
    let transaction = view.state.update({ changes: { from: 0, insert: data } });
    view.dispatch(transaction);
  } catch (error) {
    console.log(error);
  }
};

// 获取数据
const getData = () => {
  return view.state.doc.toString();
};

defineExpose({
  getData,
  clearData,
  setData
});
</script>

<style lang="scss">
.jsonCodeRoot .el-card__body {
  padding: 0;
}
</style>
